<template>
  <el-drawer
    title="编辑会员信息"
    :visible.sync="isShow"
    size="50%"
  >
    <!-- <div class="app-main-title">会员编辑</div> -->
    <div>
      <el-form
        ref="form"
        class="doumee-form"
        :rules="rulers"
        :model="param"
        label-width="120px"
        label-suffix="："
        @submit.native.prevent
      >
        <!-- <div class="property-title">编辑会员信息</div> -->
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="param.phone"
            type="text"
            placeholder="请输入手机号"
            maxlength="11"
          />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input
            v-model="param.nickName"
            type="text"
            placeholder="请输入昵称"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item v-if="fyms==='0'" label="真实姓名" prop="realName">
          <el-input v-model="param.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item v-if="fyms!=='0'" label="真实姓名">
          <el-input v-model="param.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio v-model="param.sex" label="0">保密</el-radio>
          <el-radio v-model="param.sex" label="1">男</el-radio>
          <el-radio v-model="param.sex" label="2">女</el-radio>
        </el-form-item>
        <el-form-item v-if="fyms==='0'" label="身份证号" prop="identityNumber">
          <el-input
            v-model="param.identityNumber"
            type="text"
            onkeyup="value=value.replace(/[^\X0-9]/g, '')"
            oninput="if(value.length>18)value=value.slice(0,18)"
            placeholder="请输身份证号码"
          />
        </el-form-item>
        <el-form-item v-if="fyms!=='0'" label="身份证号">
          <el-input
            v-model="param.identityNumber"
            type="text"
            onkeyup="value=value.replace(/[^\X0-9]/g, '')"
            oninput="if(value.length>18)value=value.slice(0,18)"
            placeholder="请输身份证号码"
          />
        </el-form-item>
        <el-form-item label="人脸采集" prop="showFaceUrl">
          <div class="df_ac">
            <div class="img_warp">
              <img
                :src="param.showFaceUrl ? param.showFaceUrl : faceimg"
                class="mr20"
                style="width: 80px; height: 80px"
                alt=""
              >
              <div v-show="param.showFaceUrl" class="delete pointer">
                <i
                  class="el-icon-delete icon"
                  @click.stop="deleteDeviceConfigAddImage"
                />
              </div>
            </div>
            <el-button type="primary" @click="acquisitionFace">
              <div class="df_ac">
                <img
                  src="@/assets/icon/ic_caiji.png"
                  style="width: 13px; margin-right: 6px"
                  alt=""
                >
                <span>采集</span>
              </div>
            </el-button>
            <el-button
              type="primary"
              icon="el-icon-camera"
              class="mr10"
              @click="openCamera"
            >拍摄</el-button>
            <el-upload
              class="device-uploader"
              accept=".jpg,.png"
              :auto-upload="false"
              :action="uploadFileUrl"
              :data="uploadParam"
              :show-file-list="false"
              :on-change="addFileChange"
            >
              <el-button type="primary" icon="el-icon-upload2">上传</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            :loading="editLoding"
            type="primary"
            @click="onSubmit()"
          >提交</el-button>
          <el-button
            @click="isShow = false"
          >取消</el-button>
        </el-form-item>
      </el-form>
    </div>

    <transition name="fade">
      <Cropper
        v-if="dialogCropperVisible"
        :option-img="optionImg"
        :fileinfo="fileinfo"
        use-type="MEMBER_IMG"
        :fixed-number="[500, 500]"
        @formSubmit="cropperSubmit"
        @formClose="cropperClose"
      />
    </transition>
    <el-dialog
      title="拍摄"
      :visible.sync="paisheModal"
      width="760px"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      append-to-body
      @close="closeCamera"
    >
      <video v-show="isShowCamera" id="videoCamera" :width="videoWidth" :height="videoHeight" />
      <canvas
        v-show="!isShowCamera"
        id="canvasCamera"
        style="display: none"
        :width="videoWidth"
        :height="videoHeight"
      />
      <span slot="footer">
        <div>
          <el-button @click="closeCamera">取消</el-button>
          <el-button v-show="blobFileCamera" type="primary" @click="resetCamera">重拍</el-button>
          <el-button v-show="blobFileCamera" :loading="cameraLoading" type="primary" @click="enterCamera">开始裁剪</el-button>
          <el-button v-show="!blobFileCamera" type="primary" @click="setImage">拍摄</el-button>
        </div>
      </span>
    </el-dialog>

    <CropperCopy
      v-if="isShowCropper"
      :option-img="blobFileCamera"
      use-type="MEMBER_IMG"
      :fixed-number="[500, 500]"
      @formSubmit="cropperSubmit"
      @formClose="cropperCameraClose"
    />
  </el-drawer>
</template>

<script>
import { uploadFile, changeMemberInfoPc, memberDetailInfo, configList, collectFace } from '@/api'
import Cropper from '@/components/cropper'
import CropperCopy from './cropper.vue'
export default {
  components: {
    Cropper,
    CropperCopy
  },
  data() {
    return {
      isShowCamera: true,
      cameraLoading: false,
      videoWidth: 700,
      videoHeight: 525,
      mediaStreamCamera: '',
      blobFileCamera: '',
      isShowCropper: false,
      // 以上是拍摄
      uploadFileUrl: uploadFile,
      uploadParam: {
        folder: 'MEMBER_IMG'
      },
      dialogCropperVisible: false,
      optionImg: '',
      files: {},
      fileinfo: {},
      modalDialog: this.$store.getters.dialog,
      isShowMember: false,
      caijiModal: false,
      paisheModal: false,
      xdLoding: false,
      isShow: false,
      loding: false,
      editLoding: false,
      firstQueryTime: '',
      param: {},
      fyms: '0',
      codeBtnText: '获取验证码',
      time: 60,
      codeDsiabled: false,
      linkPhone: '',
      rulers: {
        nickName: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 1, max: 8, message: '长度在 1 到 8 个字符', trigger: 'blur' }
        ],
        identityNumber: [
          { required: true, message: '请输入身份证号', trigger: 'blur' }
          // ,
          // {
          //   required: true,
          //   pattern:
          //     /^(([1-9][0-9]{5}(19|20)[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}([0-9]|X|x))|([1-9][0-9]{5}[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}))$/,
          //   message: '请输入正确的身份证号',
          //   trigger: 'blur'
          // }
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      },
      faceimg: require('@/icons/png/default_faceid.png')
    }
  },
  methods: {
    getDetail(id) {
      configList({
        param: {
          type: '7', code: 'EPIDEMIC_PREVENTION_MODE'
        }
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.fyms = res.recordList.find(item => item.code === 'EPIDEMIC_PREVENTION_MODE')
        })
        .catch((err) => {
          console.log(err)
        })
      memberDetailInfo({
        param: {
          memberId: id
        }
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.param = res.record
          this.linkPhone = this.param.phone
        })
        .catch((err) => {
          console.log(err)
        })
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.editLoding = true
          const { param } = this
          changeMemberInfoPc({
            param
          }).then(res => {
            this.editLoding = false
            if (res.errorCode === '000000') {
              this.$message.success('保存成功')
              // this.$router.go(-1)
              this.isShow = false
              this.$emit('submit')
            }
          }).catch(err => {
            this.editLoding = false
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    acquisitionFace() {
      collectFace({
        param: {
          venueId: sessionStorage.getItem('venueId'),
          shopId: sessionStorage.getItem('shopId')
        }
      }).then((res) => {
        if (res.errorCode === '000000') {
          this.$set(this.param, 'faceUrl', res.record.insertUrl)
          this.$set(this.param, 'showFaceUrl', res.record.showUrl)
        }
      })
    },
    // 打开相机
    openCamera() {
      this.paisheModal = true
      this.isShowCamera = true
      const that = this
      this.$nextTick(() => {
        var mediaOpts = { audio: false, video: true }
        navigator.mediaDevices.getUserMedia(mediaOpts).then(function(stream) {
          that.mediaStreamCamera = stream
          const video = document.querySelector('#videoCamera')
          if ('srcObject' in video) {
            video.srcObject = stream
          } else {
            video.src = window.URL && window.URL.createObjectURL(stream) || stream
          }
          video.play()
        }).catch(function(err) {
          console.log(err)
        })
      })
    },
    // 重拍
    resetCamera() {
      this.isShowCamera = true
      this.blobFileCamera = ''
      this.openCamera()
    },
    cropperCameraClose() {
      this.isShowCropper = false
      this.blobFileCamera = ''
    },
    // 关闭相机
    closeCamera() {
      this.mediaStreamCamera.getVideoTracks().forEach(function(track) {
        track.stop()
      })
      this.paisheModal = false
    },
    // 点击拍摄
    setImage() {
      const that = this
      that.isShowCamera = false
      const video = document.querySelector('#videoCamera')
      const canvas = document.querySelector('#canvasCamera')
      canvas.getContext('2d').drawImage(video, 0, 0, that.videoWidth, that.videoHeight)
      this.mediaStreamCamera.getVideoTracks().forEach(function(track) {
        track.stop()
      })
      const dataurl = canvas.toDataURL('image/jpg')
      // this.blobFileCamera = that.base64ToFile(dataurl, 'camera')
      this.blobFileCamera = dataurl
    },
    // 确认拍摄
    enterCamera() {
      this.isShowCropper = true
      this.paisheModal = false
      this.isShowCamera = true
    },
    async addFileChange(file, fileList) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      this.isShowCropper = false
      this.blobFileCamera = ''
      if (config.success) {
        this.$set(this.param, 'faceUrl', config.insertUrl)
        this.$set(this.param, 'showFaceUrl', config.showUrl)
        this.fileinfo = config
        this.dialogCropperVisible = false
      } else {
        this.$message.error(config.msg || '上传失败')
        this.dialogCropperVisible = false
      }
    },
    // async addFileChange(file, fileList) {
    //   // 上传，拿到file文件
    //   this.files = file.raw
    //   this.$nextTick(() => {
    //     this.optionImg = URL.createObjectURL(file.raw)
    //     this.fileinfo = file.raw
    //     this.dialogCropperVisible = true
    //   })
    // },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    deleteDeviceConfigAddImage(file, fileList) {
      this.param.faceUrl = ''
      this.param.showFaceUrl = ''
    }
  }
}
</script>

<style lang="scss" scoped>
.img_warp {
  display: flex;
  justify-items: center;
  align-items: center;
  position: relative;
  width: 80px;
  height: 80px;
  margin-right: 20px;
  .delete {
    background-color: rgba(0, 0, 0, 0.5);
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    display: none;
    align-items: center;
    justify-content: center;
    .icon {
      color: #fff;
    }
  }
  &:hover {
    .delete {
      display: flex;
    }
  }
}

</style>
